package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;



@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception {
        System.out.println("进入拦截器.......");
        String token = request.getHeader("token");
        if (null == token) {
            System.out.println("缺少认证信息");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            JSONObject res = new JSONObject();
            res.put("code", HttpStatus.UNAUTHORIZED.value());
            res.put("msg", "用户未经授权！");
            out.write(res.toJSONString());
            out.flush();
            out.close();
            return false; // 这里一般都是抛出自定义异常给全局异常处理，这里为了简化不做扩展说明
        }
        System.out.println("header token:" + token);
        Claims claims = JwtUtils.verifyJwt(token);
        System.out.println("认证结果:");
        if (ObjectUtils.isEmpty(claims)){
            response.setStatus(401);
            response.getWriter().append("login error");
//            response.sendError(401,"登录失败");
            return false;
//            throw exception(UNAUTHORIZED);
//            throw  new ServiceException(UNAUTHORIZED);
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
